<script lang="ts">
/**
 * @author leo
 * @description 登录页
 */

import { Component, Vue } from "vue-property-decorator";
import { namespace, Getter } from "vuex-class";
import { checkAccount, checkPassword } from "@/validate";

import LoginForm from "@/components/LoginForm.vue"; // 登录表单

const userModule = namespace("user");

@Component({
  components: {
    LoginForm
  }
})
export default class Login extends Vue {
  @Getter("version") public version!: string;
  @userModule.Action public loginByUsername!: (payload: any) => void;
  public loading: boolean = false;
  public errMessage = "";
  public codeImageUrl = "";
  public interval: any = null;
  public appName = process.env.VUE_APP_NAME;

  /**
   * 登录
   */
  public async login(
    name: string,
    password: string,
    verificationCode: number | string,
    sessionId: string,
    token: string,
    sig: string,
    scene: string,
    checkflg: number
  ): Promise<any> {
    const nameMes = checkAccount(name);
    if (nameMes) {
      this.errMessage = nameMes;
      return false;
    }

    const passwordMes = checkPassword(password);
    if (passwordMes) {
      this.errMessage = passwordMes;
      return false;
    }

    if (this.codeImageUrl && verificationCode === "") {
      this.errMessage = "请输入正确验证码";
      return false;
    }

    try {
      this.loading = true;
      await this.loginByUsername({
        username: name,
        password
      });
    } catch (error) {
      console.log(error);
    } finally {
      this.loading = false;
    }
  }

  public beforeDestroy() {
    clearInterval(this.interval);
  }
}
</script>

<template>
  <section class="login">
    <div class="login__form-wrap">
      <span class="login__text">{{appName}}</span>
      <LoginForm
        class="login__form"
        ref="LoginForm"
        :loading="loading"
        :code-image-url="codeImageUrl"
        :error-message="errMessage"
        @name-input-blur="nameInputBlur"
        @on-click-verification-code="refreshVerificationCode"
        @login="login"
      />
      <div class="login__footer">
        <span>vs {{version}}</span>
      </div>
    </div>
  </section>
</template>

<style lang="less">
.login {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #445268;
  .login__text {
    color: #fff;
    font-size: 24px;
    margin-bottom: 38px;
  }
  .login__logo {
    margin-bottom: 48px;
    width: 150px;
  }
  .login__form {
    width: 70%;
  }
  .login__form-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 600px;
    height: 400px;
  }
  .login__footer {
    margin-top: 16px;
    & > span {
      color: #909399;
    }
    a {
      cursor: pointer;
      color: #e6a23c;
      &:hover {
        color: #ec9716;
      }
    }
  }
}
</style>
